<template>
  <div class="app-container">
    <el-container>
      <el-container>
        <el-aside :width="saved ? '100%' : '63%'">
          <!-- 客户信息 -->
          <el-card class="box-card">
            <el-row :gutter="40">
              <el-col :span="12"><div class="grid-content bg-purple">客户姓名： {{ statement.customerName }}</div></el-col>
              <el-col :span="12"><div class="grid-content bg-purple">联系方式： {{ statement.customerPhone }}</div></el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="12"><div class="grid-content bg-purple">车牌号码： {{ statement.licensePlate }}</div></el-col>
              <el-col :span="12"><div class="grid-content bg-purple">汽车类型： {{ statement.carSeries }}</div></el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="12"><div class="grid-content bg-purple">服务类型： <span v-for="dict in dict.type.appoint_serv_type" :key="dict.value" ><span v-if="statement.serviceType == dict.value"> {{ dict.label }} </span></span>
              </div></el-col>
              <el-col :span="12"><div class="grid-content bg-purple">到店时间： {{ statement.actualArrivalTime }}</div></el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="12"><div class="grid-content bg-purple">总消费金额： {{ totalAmount }}</div></el-col>
              <el-col :span="12"><div class="grid-content bg-purple">实付价格： {{ totalAmount - statement.discountAmount }}</div></el-col>
            </el-row>
            <el-row :gutter="40">
              <el-col :span="12"><div class="grid-content bg-purple">优惠价格： <el-input-number size="mini" :min="0" :max="totalAmount" v-model="statement.discountAmount" :precision="2" :step="10" :disabled="saved" @change="changeBtn()"></el-input-number> </div></el-col>
            </el-row>
          </el-card>
          <br />
          <!-- 表格 -->
          <el-card>
            <!-- 按钮 -->
            <el-row :gutter="10" class="mb8" v-if="!saved">
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-circle-check"
                  size="mini"
                  v-hasPermi="['business:statementitem:edit']"
                  :disabled="saved || !saveBtn"
                  @click="save()"
                >保存</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-s-goods"
                  size="mini"
                  v-hasPermi="['business:statementitem:edit']"
                  :disabled="saved || !payBtn"
                  @click="pay()"
                >支付</el-button>
              </el-col>
            </el-row>
            <el-table
              v-loading="loading"
              :data="statementitemList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                label="服务项明细名称"
                align="center"
                prop="itemName"
              />
              <el-table-column
                label="服务项价格"
                align="center"
                prop="itemPrice"
              />
              <el-table-column
                label="购买数量"
                align="center"
                prop="itemQuantity"
              />
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                v-if="statement.status == 0"
              >
                <template slot-scope="scope">
                  <el-button
                    type="success"
                    icon="el-icon-plus"
                    @click="add(scope.row);changeBtn();" 
                    v-hasPermi="['business:statementitem:edit']"
                    circle
                    plain
                    >&nbsp;</el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-minus"
                    @click="minus(scope.row);changeBtn();" 
                    v-hasPermi="['business:statementitem:edit']"
                    circle
                    plain
                    >&nbsp;</el-button>
                </template>
              </el-table-column>
            </el-table>
              <span>显示从第 1 条到第 {{ statementitemList.length }} 条记录，共 {{ statementitemList.length }} 条记录</span>
          </el-card>

        </el-aside>
        <el-main >
          <el-card>
            <!--高级搜索  -->
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              v-show="showSearch"
              label-width="105px"
            >
              <el-form-item label="服务名称" prop="name">
                <el-input
                  v-model="itemQueryParams.name"
                  placeholder="请输入服务项名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="是否套餐" prop="carPackage">
                <el-select
                  v-model="itemQueryParams.carPackage"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.item_serv_package"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="服务分类" prop="serviceCatalog">
                <el-select
                  v-model="itemQueryParams.auditStatus"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.item_serv_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="handleQuery"
                  round
                  >搜索</el-button
                >
                
              </el-form-item>
            </el-form>
          </el-card>
          <br>
          <el-card>
            <!-- 表格 -->
            <el-table
              v-loading="loading"
              :data="itemList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column label="服务项名称" align="center" prop="name" />
              <el-table-column label="服务项价格" align="center" prop="discountPrice" />
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="success"
                    icon="el-icon-plus"
                    @click="addItem(scope.row);changeBtn();"
                    v-hasPermi="['business:statementitem:edit']"
                    circle
                    plain
                    >&nbsp;</el-button>
                </template>
              </el-table-column>
            </el-table>
            <span>显示从第 1 条到第 {{ itemList.length }} 条记录，共 {{ itemList.length }} 条记录</span>

          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { listStatementitem,allStatementitem,getStatementitem,delStatementitem,addStatementitem,updateStatementitem,saveStatementitem,payStatementitem } from "@/api/business/statementitem";

import { getStatement, editDiscountAmount } from "@/api/business/statement";
import { listItem, allItem } from "@/api/business/item";

export default {
  name: "Statementitem",
  // 服务类型
  dicts: ['appoint_serv_type',
    "item_serv_up_status",
    "item_serv_audit_status",
    "item_serv_type",
    "item_serv_package",
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 结算单明细表格数据
      statementitemList: [],
      // 服务项表格数据
      itemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 结算单参数
      statement: {
        discountAmount: 0,
      },
      // 查询参数
      queryParams: {
        statementId: null,
      },
      // 服务项查询参数
      itemQueryParams: {
        saleStatus: 1,
      },
      // 当前页 id
      statementId: null,
      // 保存状态
      saved: false,
      // 保存按钮状态
      saveBtn: false,
      // 支付按钮状态 
      payBtn: false,
    };
  },
  created() {
    // 设置ID
    this.queryParams.statementId = this.$route.params.id;
    this.statementId = this.$route.params.id;
    // 查询结算单明细
    this.getStatement()
    // 查询服务项列表
    this.getItemList();
    // 查询已上架的服务项列表
    this.getList();
    
  },
  computed: {
    // 结算单明细总金额
    totalAmount() {
      let total = 0;
      this.statementitemList.forEach((item) => {
        total += item.itemPrice * item.itemQuantity;
      });
      return total;
    },
  },
  methods: {
    // 添加已选择商品数量
    add(row) {
      this.statementitemList.forEach((item) => {
        if (item.id == row.id) {
          item.itemQuantity += 1;
          return;
        }
      });
    },
    // 减少已选择商品数量
    minus(row) {
      this.statementitemList.forEach((item) => {
        if (item.id == row.id) {
          if (item.itemQuantity <= 1) {
            this.statementitemList.splice(this.statementitemList.indexOf(item), 1);
            return;
          }
          item.itemQuantity -= 1;
          return;
        }
      });
    },
    // 添加服务项
    addItem(row) {
      // 先检测是否已经添加
      for (let i = 0; i < this.statementitemList.length; i++) {
        if (this.statementitemList[i].itemId == row.id) {
          // 如果有添加，数量+1
          this.statementitemList[i].itemQuantity += 1;
          return;
        }
      }
      // 如果没有添加，则插入
      // 遍历最大id
      let maxId = 0;
      this.statementitemList.forEach((item) => {
        if (item.id > maxId) {
          maxId = item.id;
        }
      });
      // 取出最大id
      this.statementitemList.push({
        id: maxId + 1,
        statementId: this.statementId,
        itemId: row.id,
        itemName: row.name,
        itemPrice: row.discountPrice,
        itemQuantity: 1,
      });
    },
    /** 查询结算单明细列表 */
    getList() {
      this.loading = true;
      allStatementitem(this.queryParams).then((response) => {
        this.statementitemList = response.data;
        this.loading = false;
        // 更改按钮状态
        this.payBtn = this.statementitemList.length > 0;
        this.saveBtn = false;
      });
    },
    // 查询服务项列表
    getItemList() {
      this.loading = true;
      allItem(this.itemQueryParams).then((response) => {
        this.itemList = response.data;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.getList();
      this.getItemList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 获取结算单数据
    getStatement() {
      getStatement(this.statementId).then((response) => {
        this.statement = response.data;
        // 更改保存状态
        this.saved = (this.statement.status == 1);
      });
    },
    // 保存按钮操作
    save() {
      this.$modal
        .confirm('是否保存？').then( () => {
          let query = {
            itemList: this.statementitemList,
            discountAmount: this.statement.discountAmount,
          };
          saveStatementitem(query, this.statementId).then((response) => {
            this.$modal.msgSuccess("结算单保存成功");
            this.getList();
            this.getStatement();
            this.payBtn = this.statementitemList.length > 0;
            this.saveBtn = false;
          }).catch((error) => { });
        })
    },
    changeBtn() {
      this.saveBtn = true;
      this.payBtn = false;
    },
    // 支付结算单
    pay() {
      this.$modal
        .confirm('是否支付？').then(() => {
          let query = {
            itemList: this.statementitemList,
            discountAmount: this.statement.discountAmount,
          };
          payStatementitem(query, this.statementId).then((response) => {
            this.$modal.msgSuccess("结算单支付成功");
            this.getList();
            this.getStatement();
          }).catch((error) => { });
        })
    },
  },
};
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 100%;
}

.el-aside {
  background-color: #fff;
  padding: 20px;
}

.option-btn {
  margin-bottom: 10px;
  width: 30px;
}
span, .el-col, .el-row  {
  font-size: 14px;
  color: #606266;
}
</style>